/*
 * Copyright (c) 2018.
 * This file was written by Fancyears·Milos·Malvis @connor. Any question/bug you can't post to 1243093366@qq.com.
 * ALL RIGHTS RESERVED.
 */
package org.fancyears.dao.impl;

import java.util.List;
import java.util.Random;

import org.fancyears.dao.TestDao;
import org.fancyears.helper.StringHelper;
import org.fancyears.pojo.Test;
import org.fancyears.sql.BaseSQLUtil;

/**
 * @author: Fancyears·Milos·Malvis
 * @CreateDate: 2019年1月16日 上午10:58:44
 * @Description:
 */
//注明接口，为了规范化操作，需要用到接口，否则
//@Repository(daoClass = TestDao.class)
public class TestDaoImpl extends BaseSQLUtil<Test> implements TestDao {
	private static int count = 1;
	private static TestDaoImpl dao = null;

	public static void main(String[] args) {
//		test1();
		test2();
	}

	private static void test2() {
		count = 1;
		dao = new TestDaoImpl();
		for (int i = 0; i < 20; i++) {
			Random random = new Random();
			boolean isThrowsError = random.nextBoolean();
			new Thread(new Runnable() {
				@Override
				public void run() {
					boolean go = false;
					for (int j = 0; j < 30; j++) {
						if (isThrowsError && j == 15) {
							try {
								throw new RuntimeException("自动抛出错误，回滚");
							} catch (Exception e) {
								System.out.println("回滚第" + (count) + "次");
								dao.rollback();
								count++;
							}
						}
						Test test = new Test();
						int r = random.nextInt();
						int r2 = random.nextInt();
						test.setName(StringHelper.getRandomChar(r >= 36 ? 36 : r));
						test.setLocation(StringHelper.getRandomChar(r2 >= 128 ? 128 : r2));
						try {
							dao.insert(test);
						} catch (Exception e) {
							e.printStackTrace();
						}
						go = true;
					}
					if (go) {
//						dao.sqlSession.commit();
						System.out.println("提交");
						dao.commit();
					}
				}
			}).start();
		}
	}

	@SuppressWarnings("unused")
	private static void test1() {
		count = 1;
		dao = new TestDaoImpl();
		for (int i = 0; i < 20; i++) {
			Random random = new Random();
			boolean isThrowsError = random.nextBoolean();
			new Thread(new Runnable() {
				@Override
				public void run() {
					boolean go = false;
					for (int j = 0; j < 30; j++) {
						if (isThrowsError && j == 15) {
							dao.rollback();
							System.out.println("回滚第" + (count) + "次");
							count++;
							throw new RuntimeException("自动抛出错误，回滚");
						}
						Test test = new Test();
						int r = random.nextInt();
						int r2 = random.nextInt();
						test.setName(StringHelper.getRandomChar(r >= 36 ? 36 : r));
						test.setLocation(StringHelper.getRandomChar(r2 >= 128 ? 128 : r2));
						try {
							dao.insert(test);
						} catch (Throwable e) {
							e.printStackTrace();
						}
						go = true;
					}
					if (go) {
						dao.commit();
					}
				}
			}).start();
		}
	}

	@Override
	public int insertByBatch(List<Test> params) throws Exception {
		return super.insert(params);
	}

	@Override
	public Test selectx() throws Exception {
		return super.selectOne(null);
	}

}
